package com.tinem.platform.module.starter.web.annotation;

import cn.hutool.core.util.ReflectUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: platform
 * @description: 枚举校验注解处理类
 * @author: eden#can
 * @Slogan: 没有所谓失败，除非你不再尝试
 * @date: 2021-12-09 15:28
 **/
public class EnumValueValidator implements ConstraintValidator<EnumValue, Object> {

    private Object[] values;

    @Override
    public void initialize(EnumValue constraintAnnotation) {
        String[] values = constraintAnnotation.values();
        this.values = new Object[values.length];
        if (String.class.equals(constraintAnnotation.type())) {
            this.values = values;
        }
        if (Integer.class.equals(constraintAnnotation.type())) {
            for (int i = 0; i < values.length; i++) {
                this.values[i] = Integer.parseInt(values[i]);
            }
        }
        if (BigDecimal.class.equals(constraintAnnotation.type())) {
            for (int i = 0; i < values.length; i++) {
                this.values[i] = new BigDecimal(values[i]);
            }
        }
        if (Boolean.class.equals(constraintAnnotation.type())) {
            for (int i = 0; i < values.length; i++) {
                this.values[i] = Boolean.getBoolean(values[i]);
            }
        }

        if (constraintAnnotation.type().isEnum()) {
            Method valueOf = ReflectUtil.getMethod(constraintAnnotation.type(),"valueOf",String.class);
            for (int i = 0; i < values.length; i++) {
                this.values[i] = ReflectUtil.invoke(null,valueOf,values[i]);
            }
        }
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if(value == null){
            return true;
        }
        for (Object e : values){
            if(e.equals(value)){
                return true;
            }
        }
        return false;
    }
}
